<?php

namespace Modules\Shop\Models;

use Illuminate\Support\Facades\DB;
use App\Models\BaseModel;
use App\Traits\HasCreateBy;
use App\Traits\HasStatus;
use Stancl\Tenancy\Database\Concerns\BelongsToTenant;

/**
 * Class Order.
 *
 * @package namespace Modules\Shop\Models;
 */
class Order extends BaseModel
{
    use BelongsToTenant;
    use HasCreateBy, HasStatus;

    CONST TABLE_ORDER_SKUS = 'shop_order_skus';
    CONST TABLE_ORDER_ADDRESS = 'shop_order_address';

    CONST STATUS_NOPAY = 10; //待确认 (用户下单未付款 或者 货到付款订单商家未确认)
    CONST STATUS_CONFIRMED = 20; //备货中 (用户已付款) 此状态商户才可执行发货操作 (货到付款的订单, 商家需要先确认订单才会进入此状态)
    CONST STATUS_SHIPPING = 30; //已发货 (商家出库、已发货)
    CONST STATUS_CANCEL = 40; //已取消（1.用户未支付并取消订单2.或超时未支付后系统自动取消订单3.或货到付款订单用户拒收）
    CONST STATUS_FINISHED = 50; // 已完成（在线支付订单: 商家发货后, 用户收货、拒收或者15天无物流；货到付款订单: 用户确认收货）

    // 售后状态
    CONST STATUS_AFTER_REJECTED = 80; // 退货
    CONST SATTUS_AFTER_REJECTED_CONFIRMED= 81; // 退货中-商家同意退货
    CONST SATTUS_AFTER_REJECTED_SHIPPING= 82; // 退货中-用户填写完物流
    CONST SATTUS_AFTER_REJECTED_CANCEL= 83; // 退货取消
    CONST SATTUS_AFTER_REJECTED_DONE= 85; // 退货成功

    CONST STATUS_AFTER_REFUND = 90; // 退款
    CONST STATUS_AFTER_REFUND_CONFIRMED = 91; // 退款-商家已确认，退款中
    CONST STATUS_AFTER_REFUND_CANCEL = 92; // 退款-申请取消
    CONST STATUS_AFTER_REFUND_DONE = 95; // 退款成功

    // 订单来源
    CONST ORIGIN_DOUYIN = 1;

    // 付款方式
    CONST PAY_DRIVER_AFTER = 0;
    CONST PAY_DRIVER_WEXIN = 1;
    CONST PAY_DRIVER_ALIPAY = 2;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public $table = 'shop_orders';
    protected $fillable = [
        'order_id', 'status', 'pre_total_fee', 'total_fee', 'expired_at', 'payed_at', 'tenant_id', 'msg', 'desc','pid','pay_driver',
        'express_company', 'express_no', 'delivery_at', 'receipt_at', 'create_by', 'created_at_ip', 'status_after', 'origin'
    ];

    /**
     * The attributes that are can be search =/like.
     *
     * @var array
     */
    protected $fieldSearchable = [
        'order_id' => 'like',
        'status' => '=',
        'status_after' => '='
    ];
    public static $status = [
        self::STATUS_NOPAY => '待付款',
        self::STATUS_CONFIRMED => '待发货',
        self::STATUS_SHIPPING => '已发货',
        self::STATUS_CANCEL => '已取消',
        self::STATUS_FINISHED => '已完成'
    ];
    public static $status_after = [
        self::STATUS_AFTER_REFUND => '退款中',
        self::STATUS_AFTER_REFUND_CANCEL => '退款-申请取消',
        self::STATUS_AFTER_REFUND_CONFIRMED => '退款-已确认',
        self::STATUS_AFTER_REFUND_DONE => '退款完成',

        self::STATUS_AFTER_REJECTED => '退货中',
        self::SATTUS_AFTER_REJECTED_CANCEL => '退货-已取消',
        self::SATTUS_AFTER_REJECTED_CONFIRMED => '退货-已确认',
        self::SATTUS_AFTER_REJECTED_SHIPPING => '退货-运输中',
        self::SATTUS_AFTER_REJECTED_DONE => '退货-已完成'
    ];
    public static $origins = [
        self::ORIGIN_DOUYIN => 'douyin'
    ];
    public static $paydrivers = [
        self::PAY_DRIVER_AFTER => '货到付款',
        self::PAY_DRIVER_ALIPAY => '支付宝',
        self::PAY_DRIVER_WEXIN => '微信',
    ];

    public static function boot()
    {
        parent::boot();

        self::creating(function($model) {
            $model->order_id = $model->order_id ?? self::getOrder('order_id');
            $model->created_at_ip = \request()->getClientIp();
        });
    }

    /**
     * order skus
     *
     * @return void
     */
    public function skus()
    {
        return $this->belongsToMany('Modules\Shop\Models\Sku', 'shop_order_skus', 'order_id', 'sku_id', 'order_id', 'uid')
                    ->withPivot('number', 'price_fee', 'subtotal')->with(['spu','specVals']);
    }

    public function address()
    {
        return $this->hasOne('Modules\Shop\Models\OrderAddress', 'order_id', 'order_id')->with('region');
    }


    /**
     * 下单
     *
     * @param array $skus
     * @param [type] $pre_total_fee
     * @param [type] $address
     * @param array $option
     * @return void
     */
    public static function makeOrder($skus = [], $pre_total_fee, $address, $option = [])
    {
        // 校验价格
        $_xtotal = 0;
        $orderSkus = collect();
        foreach($skus as $uid=>$number) {
            $sku = Sku::where('uid', $uid)->first();
            if($sku) {
                $subtotal = $sku->price_fee*$number;
                $orderSkus->push([
                    'sku_id' => $uid,
                    'number' => $number,
                    'price_fee' => $sku->price_fee,
                    'subtotal' => $subtotal
                ]);
                $_xtotal += $subtotal;
            }
        }

        if($_xtotal == $pre_total_fee) {
            // 实际价格跟传值一致
            return DB::transaction(function () use($pre_total_fee, $orderSkus, $address, $option) {
                $order = self::create([
                    'status' => $option['status'] ?? self::STATUS_NOPAY,
                    'pay_driver' => $option['pay_driver'] ?? '',
                    'pre_total_fee' => $pre_total_fee,
                    'expired_at' => now()->addMinutes(15),
                    'msg' => $option['msg'] ?? ''
                ]);
                $orderSkus = $orderSkus->map(function($item) use($order){
                    return array_merge($item, ['order_id' => $order->order_id]);
                })->toArray();
                DB::table(self::TABLE_ORDER_SKUS)->insert($orderSkus);
                DB::table(self::TABLE_ORDER_ADDRESS)->insert([
                    "order_id" => $order->order_id,
                    "contact_name" => $address['contact_name'],
                    "contact_phone" => $address['contact_phone'],
                    "region_id" => $address['region_id']
                ]);

                return $order;
            });
        }
        return false;
    }

    /**
     * 获取订单tab
     *
     * @return void
     */
    public static function getTabs()
    {
        $params = get_params('status');
        $items[] = ['name' => '全部', 'url' => route('shop.order.index'), 'on' => !$params];
        foreach(self::$status as $_status => $_label) {
            $items[] = ['name' => $_label, 'url' => route('shop.order.index', ['search'=>'status:'.$_status]), 'on' => $params==$_status];
        }
        $items[] = ['name' => '同步抖音小店', 'url' => '/interface/open/douyin/order/pull', 'right'=>true, 'ajax'=>true];
        if($params == self::STATUS_CONFIRMED) {
            $items[] = ['name' => '批量发货', 'url' => '/interface/open/douyin/order/pull', 'right'=>true];
        }
        return $items;
    }

    /**
     * 获取订单状态
     *
     * @return void
     */
    public function getStatusLabel()
    {
        $label = self::$status[$this->status] ?? '-';
        if($this->pay_driver == self::PAY_DRIVER_AFTER && $this->status == self::STATUS_NOPAY) {
            $label = '待确认';
        }
        return '<span class="font-bold">'.$label.'</span>';
    }

}
